﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using IGM.DataProvider;
using IGM.Framework.Commons;
using IGM.Framework.Constants;

namespace IGM.Presentation.Assignment
{
    public partial class SubcommitteeStudentsControl : UserControl
    {
        private readonly Business.Business _business;
        private List<StudentGraduation> _student;
        private List<Lecturer> _lecturers;

        public SubcommitteeStudentsControl()
        {
            InitializeComponent();
            _business = Main.Main.Instance.IgmBusiness;
        }

        private void SubcommitteeStudentsControlLoad(object sender, EventArgs e)
        {
            LoadMajor();  
            LoadCondition();
            LoadSubcommittee();
            Dock = DockStyle.Top;
        }
        private void LoadMajor()
        {
            cboMajors.DataSource = _business.GetListMajor();
            cboMajors.DisplayMember = PropertiesConstants.Name;
            cboMajors.ValueMember = PropertiesConstants.Id;
        }   
    
        private void LoadCondition()
        {
            txtCountLecturers.Text = txtCountLecturers.Text = string.Empty;
            var major = Convert.ToInt32(((Major)cboMajors.SelectedItem).Id);

            _student = _business.GetListStudentGraduation(major);
            txtCountStudents.Text = _student.Count.ToString();
            LoadStudent();
            _lecturers = _business.GetListLecturerByMajorId(major);
            txtCountLecturers.Text = _lecturers.Count.ToString();
            LoadLecturer();

            txtNumberSubcommittee.Text = (_lecturers.Count / 3).ToString();
            txtBlance.Text = (_lecturers.Count % 3).ToString();
            LoadSubcommittee();
        }

        private void LoadLecturer()
        {
            cboLecturers.DataSource = _business.GetListLecturerByMajorId(Convert.ToInt32(((Major)cboMajors.SelectedItem).Id));
            cboLecturers.DisplayMember = PropertiesConstants.Name;
            cboLecturers.ValueMember = PropertiesConstants.Id;
        }

        private void CboMajorsSelectedIndexChanged(object sender, EventArgs e)
        {
            LoadCondition();
        }

        private void PicShowSubcommitteeClick(object sender, EventArgs e)
        {
            try
            {
                // Delete old data
                _business.ClearData(3);
 
                // Insert new data          
                var subcommittees = new List<Subcommittee>();
                var numberSubcommittee = Convert.ToInt32(txtNumberSubcommittee.Text.Trim());
                for (var i = 0; i < numberSubcommittee; i++)
                {
                    subcommittees.Add(new Subcommittee
                    {
                        Name = string.Format(DateTime.Now + "_Tiểu ban {0}", i + 1),
                        IdKindIntern = 3,
                        IdMajor = Convert.ToInt32(((Major)cboMajors.SelectedItem).Id),
                        NumberMembers = 3
                    });
                }

                if (subcommittees.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }
                _business.AddSubcommittee(subcommittees);
                dgvSubcommitteeList.DataSource = _business.GetSubcommitteeByKindInternId(3, ((Major)cboMajors.SelectedItem).Id);

                LoadSubcommittee();
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        #region -- Subcommittee --

        private void LoadSubcommittee()
        {
            dgvSubcommitteeList.DataSource = _business.GetSubcommitteeByKindInternId(3, ((Major)cboMajors.SelectedItem).Id);
            DataGridViewHelper.ShowHideColumns(dgvSubcommitteeList,
                                               new[] { PropertiesConstants.IsChecked, PropertiesConstants.Name, "NumberMembers" });
            DataGridViewHelper.ShowIsCheck(dgvSubcommitteeList);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvSubcommitteeList, false);
            DataGridViewHelper.ChangeDgvHeaderText(dgvSubcommitteeList, new[] { "IsChecked", "Name", "NumberMembers" },
                                                   new[] { "Chọn", "Tên tiểu ban", "Số lượng thành viên" });
            SubcommitteeCurrentRowChanged();
        }

        private void SubcommitteeCurrentRowChanged()
        {
            if (dgvSubcommitteeList.CurrentRow != null)
            {
                txtName.Text = dgvSubcommitteeList.CurrentRow.Cells["Name"].Value.ToString();
                lblSubcommitteeLecturer.Text = string.Format(ConstantMessages.LblSubcommitteeLecturer, txtName.Text);

                LoadSubcommitteeLecturers();
                LoadSubcommitteeStudents();
            }

            else
            {
                txtName.Text = string.Empty;
                ckbAllSubcommittees.Checked = false;
                dgvSubcommitteeStudent.DataSource = null;
                dgvSubcommitteeLecturer.DataSource = null;
            }
        }

        private void DgvSubcommitteeListCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvSubcommitteeList == null ||
               dgvSubcommitteeList.Columns[(string)typeof(Subcommittee).Properties().IsChecked] == null ||
               dgvSubcommitteeList.Columns[(string)typeof(Subcommittee).Properties().IsChecked].Index != e.ColumnIndex)
                return;

            dgvSubcommitteeList[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvSubcommitteeList[e.ColumnIndex, e.RowIndex].Value;

            ckbAllSubcommittees.Checked = DataGridViewHelper.AllRowsIsCheck(dgvSubcommitteeList);
        }

        private void DgvSubcommitteeListCurrentCellChanged(object sender, EventArgs e)
        {
            SubcommitteeCurrentRowChanged();
        }

        private void CkbAllSubcommitteesCheckedChanged(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvSubcommitteeList, ckbAllSubcommittees.Checked);
        }

        private void ReloadSubcommittee(Subcommittee subcommittee)
        {
            LoadSubcommittee();
            DataGridViewHelper.SetDgvCurrentCell(dgvSubcommitteeList, subcommittee.Name);
            SubcommitteeCurrentRowChanged();
        }

        private void BtnAddSubcommitteesClick(object sender, EventArgs e)
        {
            try
            {
                var subcommittee = new Subcommittee
                {
                    Name = txtName.Text.Trim(),
                    IdKindIntern = 3,
                    IdMajor = Convert.ToInt32(((Major)cboMajors.SelectedItem).Id),
                    NumberMembers = 3
                };

                string message;

                if (_business.AddSubcommitteeValidator(subcommittee, out message))
                {
                    _business.AddSubcommittee(subcommittee);

                    ReloadSubcommittee(subcommittee);
                }
                else
                    MessageBox.Show(message);

            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnDeleteSubcommitteesClick(object sender, EventArgs e)
        {
            try
            {
                var subcommittees = new List<Subcommittee>();
                string message;

                for (var i = 0; i < dgvSubcommitteeList.RowCount; i++)
                {
                    if (!(bool)dgvSubcommitteeList[(string)typeof(Subcommittee).Properties().IsChecked, i].Value) continue;

                    subcommittees.Add(new Subcommittee
                    {
                        Id = (int)dgvSubcommitteeList[(string)typeof(Subcommittee).Properties().Id, i].Value,
                        Name = dgvSubcommitteeList[(string)typeof(Subcommittee).Properties().Name, i].Value.ToString(),
                        IdKindIntern = Convert.ToInt32(dgvSubcommitteeList["IdKindIntern", i].Value),
                        IdMajor = Convert.ToInt32(dgvSubcommitteeList["IdMajor", i].Value),
                        NumberMembers = 3
                    });
                }
                if (subcommittees.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }

                if (!_business.DeleteSubcommitteesValidator(subcommittees, out message))
                    MessageBox.Show(message);

                if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các tiểu ban đã chọn"), FileConstants.ProgramName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    _business.DeleteSubcommittees(subcommittees);
                    ReloadSubcommittee(null);
                }
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnEditSubcommitteesClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvSubcommitteeList.CurrentRow != null)
                {
                    var subcommittee = new Subcommittee
                    {
                        Id = Convert.ToInt32(dgvSubcommitteeList.CurrentRow.Cells[PropertiesConstants.Id].Value),
                        Name = txtName.Text.Trim(),
                        IdKindIntern = Convert.ToInt32(dgvSubcommitteeList.CurrentRow.Cells["IdKindIntern"].Value),
                        IdMajor = Convert.ToInt32(dgvSubcommitteeList.CurrentRow.Cells["IdMajor"].Value),
                        NumberMembers = Convert.ToInt32(dgvSubcommitteeList.CurrentRow.Cells["NumberMembers"].Value)
                    };
                    string message;
                    if (_business.EditSubcommitteeValidator(subcommittee, out message))
                    {
                        if (!_business.EditSubcommittee(subcommittee))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.ProgramName);
                            return;
                        }
                        ReloadSubcommittee(subcommittee);
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
            }

            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        #endregion

        #region -- Subcommittee Lecturer --

        private void LoadSubcommitteeLecturers()
        {
            if (dgvSubcommitteeList.CurrentRow != null)
                dgvSubcommitteeLecturer.DataSource = _business.GetLecturerBySubcommitteeId((int)dgvSubcommitteeList.CurrentRow.Cells["Id"].Value);

            if (dgvSubcommitteeLecturer.DataSource == null)
                return;

            DataGridViewHelper.ShowHideColumns(dgvSubcommitteeLecturer,
                                               new[] { PropertiesConstants.IsChecked, "LecturerName" });
            DataGridViewHelper.ShowIsCheck(dgvSubcommitteeLecturer);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvSubcommitteeLecturer, false);
            DataGridViewHelper.ChangeDgvHeaderText(dgvSubcommitteeLecturer, new[] { "IsChecked", "LecturerName" },
                                                   new[] { "Chọn", "Giảng viên" });
            SubcommitteeLecturersCurrentRowChanged();
        }       

        private void SubcommitteeLecturersCurrentRowChanged()
        {
            if (dgvSubcommitteeLecturer.CurrentRow != null)
                cboLecturers.Text = dgvSubcommitteeLecturer.CurrentRow.Cells["LecturerName"].Value.ToString();
            else
            {
                cboLecturers.SelectedIndex = -1;
                ckbSubcommitteeLecturer.Checked = false;
            }
        }

        private void DgvSubcommitteeLecturerCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvSubcommitteeLecturer == null ||
               dgvSubcommitteeLecturer.Columns[(string)typeof(SubcommitteeLecturer).Properties().IsChecked] == null ||
               dgvSubcommitteeLecturer.Columns[(string)typeof(SubcommitteeLecturer).Properties().IsChecked].Index != e.ColumnIndex)
                return;

            dgvSubcommitteeLecturer[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvSubcommitteeLecturer[e.ColumnIndex, e.RowIndex].Value;

            ckbSubcommitteeLecturer.Checked = DataGridViewHelper.AllRowsIsCheck(dgvSubcommitteeLecturer);
        }

        private void DgvSubcommitteeLecturerCurrentCellChanged(object sender, EventArgs e)
        {
            SubcommitteeLecturersCurrentRowChanged();
        }

        private void CkbSubcommitteeLecturerCheckedChanged(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvSubcommitteeLecturer, ckbSubcommitteeLecturer.Checked);
        }

        private void ReloadSubcommitteeLecturer(SubcommitteeLecturer subcommittee)
        {
            LoadSubcommitteeLecturers();
            DataGridViewHelper.SetDgvCurrentCell(dgvSubcommitteeLecturer, subcommittee.LecturerName);
            SubcommitteeCurrentRowChanged();
        }

        private void BtnAddSubcommitteeLecturerClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvSubcommitteeList.CurrentRow != null && dgvSubcommitteeLecturer.RowCount < 3)
                {
                    var subcommittee = new SubcommitteeLecturer
                    {
                        IdSubcommittee = Convert.ToInt32(dgvSubcommitteeList.CurrentRow.Cells["Id"].Value),
                        IdLecturer = Convert.ToInt32(((Lecturer)cboLecturers.SelectedItem).Id)
                    };

                    string message;

                    if (_business.AddSubcommitteeLecturerValidator(subcommittee, out message))
                    {
                        _business.AddSubcommitteeLecturer(subcommittee);

                        ReloadSubcommitteeLecturer(subcommittee);                        
                    }
                    else
                        MessageBox.Show(message);
                }
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnDeleteSubcommitteeLecturersClick(object sender, EventArgs e)
        {
            try
            {
                var subcommittees = new List<SubcommitteeLecturer>();
                string message;
                for (var i = 0; i < dgvSubcommitteeLecturer.RowCount; i++)
                {
                    if (!(bool)dgvSubcommitteeLecturer[(string)typeof(SubcommitteeLecturer).Properties().IsChecked, i].Value) continue;

                    subcommittees.Add(new SubcommitteeLecturer
                    {
                        Id = (int)dgvSubcommitteeLecturer[(string)typeof(SubcommitteeLecturer).Properties().Id, i].Value,
                        IdSubcommittee = Convert.ToInt32(dgvSubcommitteeLecturer["IdSubcommittee", i].Value),
                        IdLecturer = Convert.ToInt32(dgvSubcommitteeLecturer["IdLecturer", i].Value),
                    });
                }
                if (subcommittees.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }

                if (_business.DeleteSubcommitteeLecturerValidator(subcommittees, out message))
                {
                    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các thành viên tiểu ban đã chọn"), FileConstants.ProgramName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteSubcommitteeLecturer(subcommittees);
                        ReloadSubcommitteeLecturer(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }
       
        #endregion

        #region -- Subcommittee Students --

        private void LoadSubcommitteeStudents()
        {
            if (dgvSubcommitteeList.CurrentRow != null)
                dgvSubcommitteeStudent.DataSource = _business.GetStudentBySubcommitteeId((int)dgvSubcommitteeList.CurrentRow.Cells["Id"].Value);

            if (dgvSubcommitteeStudent.DataSource == null)
                return;

            DataGridViewHelper.ShowHideColumns(dgvSubcommitteeStudent,
                                               new[] { PropertiesConstants.IsChecked, "StudentName", "StudentCode" });
            DataGridViewHelper.ShowIsCheck(dgvSubcommitteeStudent);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvSubcommitteeStudent, false);
            DataGridViewHelper.ChangeDgvHeaderText(dgvSubcommitteeStudent, new[] { "IsChecked", "StudentName", "StudentCode" },
                                                   new[] { "Chọn", "Tên sinh viên", "Mã sinh viên" });
            SubcommitteeStudentsCurrentRowChanged();
        }

        private void LoadStudent()
        {
            cboStudents.DataSource = _business.GetListStudentGraduation(Convert.ToInt32(((Major)cboMajors.SelectedItem).Id));
            cboStudents.DisplayMember = PropertiesConstants.Name;
            cboStudents.ValueMember = PropertiesConstants.Id;
        }

        private void SubcommitteeStudentsCurrentRowChanged()
        {
            if (dgvSubcommitteeStudent.CurrentRow != null)
                cboStudents.Text = dgvSubcommitteeStudent.CurrentRow.Cells["StudentName"].Value.ToString();
            else
            {
                cboStudents.SelectedIndex = -1;
                ckbSubcommitteeLecturer.Checked = false;
            }
        }

        private void DgvSubcommitteeStudentCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvSubcommitteeStudent == null ||
               dgvSubcommitteeStudent.Columns[(string)typeof(SubcommitteeStudent).Properties().IsChecked] == null ||
               dgvSubcommitteeStudent.Columns[(string)typeof(SubcommitteeStudent).Properties().IsChecked].Index != e.ColumnIndex)
                return;

            dgvSubcommitteeStudent[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvSubcommitteeStudent[e.ColumnIndex, e.RowIndex].Value;

            ckbSubcommitteeStudent.Checked = DataGridViewHelper.AllRowsIsCheck(dgvSubcommitteeStudent);
        }

        private void DgvSubcommitteeStudentCurrentCellChanged(object sender, EventArgs e)
        {
            SubcommitteeStudentsCurrentRowChanged();
        }

        private void CkbSubcommitteeStudentCheckedChanged(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvSubcommitteeStudent, ckbSubcommitteeStudent.Checked);
        }

        private void ReloadSubcommitteeStudent(SubcommitteeStudent subcommittee)
        {
            LoadSubcommitteeStudents();
            DataGridViewHelper.SetDgvCurrentCell(dgvSubcommitteeStudent, subcommittee.StudentCode);
            SubcommitteeCurrentRowChanged();
        }

        private void BtnAddSubcommitteeStudentClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvSubcommitteeList.CurrentRow != null)
                {
                    var subcommittee = new SubcommitteeStudent
                    {
                        IdSubcommittee = Convert.ToInt32(dgvSubcommitteeList.CurrentRow.Cells["Id"].Value),
                        IdStudent = Convert.ToInt32(((StudentGraduation)cboStudents.SelectedItem).Id)
                    };                    
                    string message;                   
                    if (_business.AddSubcommitteeStudentValidator(subcommittee, out message))
                    {
                        _business.AddSubcommitteeStudent(subcommittee);
                        ReloadSubcommitteeStudent(subcommittee);
                    }
                    else
                        MessageBox.Show(message);
                }
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnDeleteSubcommitteeStudentsClick(object sender, EventArgs e)
        {
            try
            {
                var subcommittees = new List<SubcommitteeStudent>();
                string message;
                for (var i = 0; i < dgvSubcommitteeStudent.RowCount; i++)
                {
                    if (!(bool)dgvSubcommitteeStudent[(string)typeof(SubcommitteeStudent).Properties().IsChecked, i].Value) continue;

                    subcommittees.Add(new SubcommitteeStudent
                    {
                        Id = (int)dgvSubcommitteeStudent[(string)typeof(SubcommitteeStudent).Properties().Id, i].Value,
                        IdSubcommittee = Convert.ToInt32(dgvSubcommitteeStudent["IdSubcommittee", i].Value),
                        IdStudent = Convert.ToInt32(dgvSubcommitteeStudent["IdStudent", i].Value),
                    });
                }
                if (subcommittees.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }

                if (_business.DeleteSubcommitteeStudentsValidator(subcommittees, out message))
                {
                    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các sinh viên thuộc tiểu ban đã chọn"), FileConstants.ProgramName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteSubcommitteeStudents(subcommittees);
                        ReloadSubcommitteeStudent(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }       
        #endregion        
    }
}
